//
//  WmcDevNetworkUploadVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/6/24.
//

import JXPhotoBrowser
import UIKit

// MARK: - [WmcDevNetworkUploadVC]

class WmcDevNetworkUploadVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "上传图片"
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)

        addSubview(tableView)
        addSubview(sureBtn)

        tableView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(sureBtn.snp.top).offset(-20)
        }

        sureBtn.snp.makeConstraints { make in
            make.top.equalTo(tableView.snp.bottom).offset(50)
            make.bottom.equalTo(-Wmc_safeAreaBottom - 30)
            make.height.equalTo(50)
            make.left.equalTo(20)
            make.right.equalTo(-20)
        }
    }

    // Private

    private lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("选择照片", for: .normal)
        btn.setBackgroundImage(UIColor.wmc_yellow_FFC400.yp.uiImage, for: .normal)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(onSureAction(_:)), for: .touchUpInside)
        return btn
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcDevNetworkUploadCell.self, forCellReuseIdentifier: "WmcDevNetworkUploadCell")
        view.separatorStyle = .none
        return view
    }()

    private lazy var dataSource: [WmcUploadTestModel] = {
        return []
    }()

    @objc
    private func onSureAction(_ sender: UIButton) {
        pushImageBrowse()
    }

    private func pushImageBrowse() {
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            self.selectPhoto()
        } else {
            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
        }
    }

    private func selectPhoto() {
        WmcPhotoSelectManager.photoSelect(vc: YPApp.CurrentVC, maxCount: 9) { imgs in

            var arr: [WmcUploadTestModel] = []

            for (idx, image) in imgs.enumerated() {
                var model = WmcUploadFileModel()
                model.entryId = 100002
                model.type = 2
                model.format = "png"
                model.wmcInfo = [:]
                model.uid = Int(WmcLoginManager.shared.yupaoAccountModel?.userId ?? "0")
                model.uid = 0
                model.takeTime = Date().yp.string(.iso8601Day)

                let m = WmcUploadTestModel()
                m.params = model

                if let data = image.pngData() {
                    m.data = data
                }

                m.progress = { value in
                    m.progressValue = value
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }

                m.uploadStatus = { status in
                    print("第\(idx)任务 status \(status)")
                    if idx == 5 {
                        if status == .uploading {
                            m.cancel?()
                        }
                    }
                    m.status = status
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }

                arr.append(m)
            }

            self.dataSource = arr
            self.tableView.reloadData()

            self.upload()
        }
    }

    private func upload() {
        WmcUploadManager.uploadMultiFiles(dataSource) { progress in
            print("total progress: \(progress)")
        } completion: {_ in
            print("全部上传成功!")
        } failure: { error in
            print("有任务上传失败")
        }
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcDevNetworkUploadVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcDevNetworkUploadCell = tableView.dequeueReusableCell(withIdentifier: "WmcDevNetworkUploadCell", for: indexPath) as! WmcDevNetworkUploadCell
        let model = dataSource[indexPath.row]
        cell.bindModel(model, idx: indexPath.row)
        return cell
    }

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
        return 110
    }
}
